<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/10/7
 * Time: 10:51
 */
namespace App\Http\Controllers\Api;

use App\Service\Api\HistoryService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Constant\ErrorConstant;

class HistoryController extends BaseController
{
    protected $service;

    public function __construct(Request $request, HistoryService $service)
    {
        parent::__construct($request);
        $this->service  =   $service;
    }

    /**
     * 保留搜索记录
     * @return \Illuminate\Http\JsonResponse
     */
    public function searchHistory()
    {
        $validator  =   Validator::make($this->request->post(), [
            'search_word'   =>  'required|string',
        ], [
            'search_word.required'  =>  '搜索词条不能为空',
            'search_word.string'    =>  '搜索词条必须为字符'
        ]);

        if ($validator->fails()) {
            return $this->errorResponse(ErrorConstant::API_HISTORY_SAVE_ERROR, $validator->errors()->first());
        }

        [$flag, $result]    =   $this->service->historySearch($this->request->post('search_word'));
        if ($flag) {
            return $this->successResponse($result);
        } else {
            return $this->errorResponse(ErrorConstant::API_HISTORY_SAVE_ERROR, $result);
        }
    }

    /**
     * 用户搜索记录删除
     * @return \Illuminate\Http\JsonResponse
     */
    public function clearHistory()
    {
        [$flag, $result]    =   $this->service->historyClear();
        if ($flag) {
            return $this->successResponse($result);
        } else {
            return $this->errorResponse(ErrorConstant::API_HISTORY_CLEAR_ERROR, $result);
        }
    }

    /**
     * 用户搜索记录显示
     * @return \Illuminate\Http\JsonResponse
     */
    public function listHistory()
    {
        [$flag, $result]    =   $this->service->historyList();
        if ($flag) {
            return $this->successResponse($result);
        } else {
            return $this->errorResponse(ErrorConstant::API_HISTORY_LIST_ERROR, $result);
        }
    }

}
